<template>
  <div id="house">
    <div class="bottom-page" ref="bottom">
      <div class="head-line">
        <img src="@/assets/icon/arrow-l.png" @click="$router.go(-1)" alt />
        <h2>房屋详情</h2>
        <span></span>
      </div>
      <div class="houseInfor">
        <h1>房屋基本信息</h1>
        <p>户主：{{ house.name }}</p>
        <p>身份证号: {{ house.idcard }}</p>
        <p>门牌号: {{ house.doorno }}</p>
        <p>房型: {{ house.housetype }}</p>
        <p>结构类型: {{ house.structure }}</p>
        <p>验收标准: {{ house.projectstatus }}</p>
        <p>所在村组：{{ house.village }} {{ house.address }}</p>
      </div>
      <div class="inspect-list">
        <div class="inspect-head">
          <h1>房屋巡查记录</h1>
          <div class="add" @click="showD()">新增</div>
        </div>
        <div class="table">
          <div class="inspect-title">
            <span v-for="item in titleList" :key="item">{{ item }}</span>
          </div>
          <div class="inspect-item" v-for="item in inspectList" :key="item.id">
            <span>{{ item.projectstatus }}</span>
            <span>{{ formatDate(item.checkdate) }}</span>
            <span>{{ item.localedescribe }}</span>
            <span>{{ item.isrectify }}</span>
            <span @click="showD(item)">查看</span>
          </div>
        </div>
      </div>
    </div>
    <!-- 巡查详情弹出层 -->
    <div class="demo-out" v-if="showDemo">
      <!-- <img src="@/assets/icon/close.svg" alt="" @click="showDemo = false" /> -->
      <div class="demo-in">
        <div class="demo-inner">
          <div><span>户主：</span> {{ house.name }}</div>
          <div><span>门牌号：</span> {{ house.doorno }}</div>
          <div><span>工程状态：</span> {{ house.projectstatus }}</div>
          <div>
            <span>所在村组：</span> {{ house.village }} {{ house.address }}
          </div>
          <div>
            <span> 巡查人： </span>
            <input type="text" v-model="demoObj.checker" />
          </div>
          <div>
            <span>巡查时间： </span>
            <input
              type="text"
              v-model="demoObj.checkdate"
              @focus="showPicker = true"
            />
          </div>
          <div>
            <span>现场照片：</span>
            <van-uploader
              v-model="XCfileList"
              :after-read="XCRead"
              :max-count="1"
            />
            <!-- <input
            type="file"
            name=""
            id=""
            ref="img"
            accept="image/*"
            @change="getimg"
          /> -->
          </div>
          <div class="textarea">
            <span>现场情况：</span>
            <textarea
              name=""
              id=""
              cols="30"
              rows="4"
              v-model="demoObj.localedescribe"
            ></textarea>
          </div>
          <div>
            <span>是否需要整改：</span>
            <van-switch v-model="demoObj.isrectify" size="30px" />
            {{ demoObj.isrectify ? "是" : "否" }}
          </div>
          <div class="rectifyDemo" v-if="demoObj.isrectify">
            <div>
              <span>整改是否完成：</span>
              <van-switch v-model="demoObj.iscompelte" size="30px" />
              {{ demoObj.iscompelte ? "是" : "否" }}
            </div>
            <div>
              <span>整改证明：</span>
              <van-uploader
                v-model="ZMfileList"
                :after-read="ZMRead"
                :max-count="1"
              />
            </div>
            <div>
              <span>整改完成现场照片：</span>
              <van-uploader
                v-model="WCfileList"
                :after-read="WCRead"
                :max-count="1"
              />
            </div>
            <div class="textarea">
              <span>整改措施：</span>
              <textarea
                name=""
                id=""
                cols="30"
                rows="4"
                v-model="demoObj.rectifystep"
              ></textarea>
            </div>
          </div>
        </div>
        <div class="btns">
          <button @click="cancelSubmit">取消</button>
          <button @click="submit">确定</button>
        </div>
      </div>
      <van-popup v-model="showPicker" position="bottom">
        <van-datetime-picker
          v-model="pickTime"
          :item-height="optionHeight"
          type="date"
          show-toolbar
          :min-date="minDate"
          :max-date="maxDate"
          @cancel="onCancel"
          @confirm="onConfirm"
        />
      </van-popup>
    </div>
  </div>
</template>

<script>
import api from "@/api/api.js";
import axios from "axios";
import local from "@/util/localstorage.js";

export default {
  name: "house",
  data() {
    return {
      house: {},
      inspectList: [],
      titleList: ["工程状态", "巡查时间", "现场情况", "是否整改", "操作"],
      showDemo: false,
      showPicker: false,
      demoObj: {
        isrectify: false,
        checkdate: "",
      },
      optionHeight: 60,
      minDate: new Date("1990-01-01"),
      maxDate: new Date("2030-01-01"),
      // 选择器内的时间   如果直接绑定obj内的时间则造成滑动的时候就直接改变
      pickTime: new Date(),
      XCfileList: [],
      // XCfileIdlist: [],
      ZMfileList: [],
      // ZMfileIdlist: [],
      WCfileList: [],
      // WCfileIdlist: [],
    };
  },
  computed: {
    checkdate() {
      return this.formatDate();
    },
  },
  methods: {
    // 获取房屋数据
    getMore() {
      let id = this.$route.params.id;
      api.getHouseMore({ id }).then((res) => {
        // console.log(res.data.jsonData.housePatrolList);
        this.house = res.data.jsonData.houseBase;
        this.inspectList = res.data.jsonData.housePatrolList;
      });
    },
    // 格式化时间戳     自定义返回  年月日时分秒
    formatDate(date) {
      var now = new Date(date);
      var year = now.getFullYear();
      // var year = now.getYear();     //  为啥是120
      // console.log(year);
      var month = now.getMonth() + 1;
      // if (month < 10) {
      //   month = "0" + month;
      // }
      month = (month + "").padStart(2, "0");
      var date = now.getDate();
      // if (date < 10) {
      //   date = "0" + date;
      // }
      date = (date + "").padStart(2, "0");
      var hour = now.getHours();
      var minute = now.getMinutes();
      var second = now.getSeconds();
      return year + "-" + month + "-" + date;
    },
    // 新增或者查看按钮
    showD(obj) {
      console.log(obj);
      this.showDemo = true;
      this.demoObj.checkdate = this.formatDate(this.pickTime);
      this.demoObj.checker = local.getLoaclStorage("userInfo").fullname;
      this.$nextTick(() => {
        // document.querySelector(".demo-out").ontouchmove = function (e) {
        //   // console.log(e.target);
        //   if (e.target.tagName !== 'TEXTAREA') {
        //     e.stopPropagation();
        //     e.preventDefault();
        //   }
        // };
      });
      if (obj) {
        Object.assign(this.demoObj, obj);
        this.demoObj.isrectify = this.demoObj.isrectify == "是" ? true : false;
        this.demoObj.iscompelte =
          this.demoObj.iscompelte == "是" ? true : false;
        this.demoObj.checkdate = this.formatDate(this.demoObj.checkdate);
        if (obj.picture) {
          let item = {
            content: JSON.parse(obj.picture).attachs[0].fileSrc,
          };
          this.XCfileList[0] = item;
        }
      }
    },
    // 时间选择器的取消
    onCancel() {
      this.pickTime = new Date(this.demoObj.checkdate);
      this.showPicker = false;
      // this.demoObj.isrectify = false;
    },
    // 时间选择器的确定
    onConfirm(value) {
      // console.log('点击到确定按钮了', value);
      this.pickTime = value;
      this.demoObj.checkdate = this.formatDate(value);
      this.showPicker = false;
    },
    XCRead(file) {
      // 此时可以自行将文件上传至服务器
      console.log(file.content);

      let afterCompressBase64 = this.compressImg(
        file.content,
        1080,
        0.5
      );
        // file.file.size,
      afterCompressBase64.then((res) => {
        console.log(res)
      });

      var formdata1 = new FormData(); // 创建form对象
      formdata1.append("img", file.file, file.file.name); // 通过append向form对象添加数据,可以通过append继续添加数据
      let config = {
        headers: { "Content-Type": "multipart/form-data" },
      }; //添加请求头
      axios
        .post(
          "http://house.ksljz.cn:8081/house/platform/system/sysFile/fileUpload.do",
          formdata1,
          config
        )
        .then((response) => {
          //这里的/xapi/upimage为接口
          console.log(response.data);
          this.demoObj.picture = {
            attachs: [{ fileId: response.data.fileId, fileSrc: file.content }],
          };
          this.demoObj.picture = JSON.stringify(this.demoObj.picture);
        });
    },
    ZMRead(file) {
      // 此时可以自行将文件上传至服务器
      console.log(file.file);
      var formdata1 = new FormData(); // 创建form对象
      formdata1.append("img", file.file, file.file.name); // 通过append向form对象添加数据,可以通过append继续添加数据
      let config = {
        headers: { "Content-Type": "multipart/form-data" },
      }; //添加请求头
      console.log(formdata1);
      axios
        .post(
          "http://house.ksljz.cn:8081/house/platform/system/sysFile/fileUpload.do",
          formdata1,
          config
        )
        .then((response) => {
          //这里的/xapi/upimage为接口
          console.log(response.data);
          this.demoObj.zgzmfile = {
            attachs: [{ fileId: response.data.fileId, fileSrc: file.content }],
          };
          this.demoObj.zgzmfile = JSON.stringify(this.demoObj.zgzmfile);
        });
    },
    WCRead(file) {
      // 此时可以自行将文件上传至服务器
      console.log(file.file);
      var formdata1 = new FormData(); // 创建form对象
      formdata1.append("img", file.file, file.file.name); // 通过append向form对象添加数据,可以通过append继续添加数据
      let config = {
        headers: { "Content-Type": "multipart/form-data" },
      }; //添加请求头
      console.log(formdata1);
      axios
        .post(
          "http://house.ksljz.cn:8081/house/platform/system/sysFile/fileUpload.do",
          formdata1,
          config
        )
        .then((response) => {
          //这里的/xapi/upimage为接口
          console.log(response.data);
          this.demoObj.zgwcxczpfile = {
            attachs: [{ fileId: response.data.fileId, fileSrc: file.content }],
          };
          this.demoObj.zgwcxczpfile = JSON.stringify(this.demoObj.zgwcxczpfile);
        });
    },
    cancelSubmit() {
      this.showDemo = false;
      this.demoObj = this.$options.data().demoObj;
      this.XCfileList = [];
    },
    submit() {
      var obj = {
        id: this.demoObj.id,
        houseid: this.$route.params.id,
        name: this.house.name,
        doorno: this.house.doorno,
        address: this.house.address,
        village: this.house.village,
        town: this.house.town,
        xy: this.house.xy,
        projectstatus: this.house.projectstatus,
        checker: this.demoObj.checker,
        checkdate: this.demoObj.checkdate,
        localedescribe: this.demoObj.localedescribe,
        picture: this.demoObj.picture, // 现场照片
        isrectify: this.demoObj.isrectify ? "是" : "否",
        rectifystep: this.demoObj.rectifystep,
        iscompelte: this.demoObj.iscompelte ? "是" : "否",
        attach: "",
        remark: "",
        zgzmfile: this.demoObj.zgzmfile, // 整改证明图片
        zgwcxczpfile: this.demoObj.zgwcxczpfile, // 整改完成照片
        createBy: this.demoObj.checker,
        createtime: new Date(),
        updatetime: null,
        updateBy: null,
        runId: null,
      };
      if (this.demoObj.id) {
        obj.createBy = this.demoObj.createBy;
        // obj.createtime = this.demoObj.createtime + '';
        obj.createtime = "";
        obj.updatetime = new Date();
        obj.updateBy = this.demoObj.checker;
      }
      var jsonData = JSON.stringify(obj);
      api.saveInspect(obj).then((res) => {
        console.log(res);
        if (res.data.success) {
          this.$toast.success("成功");
          this.cancelSubmit();
        } else {
          this.$toast.fail("失败");
          this.cancelSubmit();
        }
        setTimeout(() => {
          this.getMore();
        }, 2000);
      });
    },

    resizeImg() {
      console.log(file);
      var fileType = file.type;
      if (fileType.indexOf("image") < 0) {
        this.$message.warning("请上传图片");
        return false;
      }
      //TODO 验证文件大小

      // 压缩图片需要的一些元素和对象
      var reader = new FileReader(),
        img = new Image();
      // 选择的文件对象
      // var file = null

      if (file.type.indexOf("image") == 0) {
        reader.readAsDataURL(file);
      }
      // 文件base64化，以便获知图片原始尺寸
      reader.onload = function (e) {
        img.src = e.target.result;
      };

      // 缩放图片需要的canvas
      var canvas = document.createElement("canvas");
      var context = canvas.getContext("2d");

      var that = this;
      // base64地址图片加载完毕后
      img.onload = function () {
        // 图片原始尺寸
        var originWidth = this.width;
        var originHeight = this.height;
        // 最大尺寸限制
        var maxWidth = 1920,
          maxHeight = 1080;
        // 目标尺寸
        var targetWidth = originWidth,
          targetHeight = originHeight;
        console.log(targetWidth, targetHeight);
        // 图片尺寸超过400x400的限制
        if (originWidth > maxWidth || originHeight > maxHeight) {
          if (originWidth / originHeight > maxWidth / maxHeight) {
            // 更宽，按照宽度限定尺寸
            targetWidth = maxWidth;
            targetHeight = Math.round(maxWidth * (originHeight / originWidth));
          } else {
            targetHeight = maxHeight;
            targetWidth = Math.round(maxHeight * (originWidth / originHeight));
          }

          // canvas对图片进行缩放
          canvas.width = targetWidth;
          canvas.height = targetHeight;
          // 清除画布
          context.clearRect(0, 0, targetWidth, targetHeight);
          // 图片压缩
          context.drawImage(img, 0, 0, targetWidth, targetHeight);
          var getMimeType = function (urlData) {
            var arr = urlData.split(",");
            var mime = arr[0].match(/:(.*?);/)[1];
            return mime;
          };
          // canvas转为base
          var base64 = canvas.toDataURL(getMimeType(base64String), quality);
        }
      };
    },
    compressImg(base64String, w, quality) {
      var getMimeType = function (urlData) {
        var arr = urlData.split(",");
        var mime = arr[0].match(/:(.*?);/)[1];
        return mime;
      };
      var newImage = new Image();
      var imgWidth, imgHeight;

      var promise = new Promise((resolve) => (newImage.onload = resolve));
      newImage.src = base64String;
      return promise.then(() => {
        imgWidth = newImage.width;
        imgHeight = newImage.height;
        var canvas = document.createElement("canvas");
        var ctx = canvas.getContext("2d");
        if (Math.max(imgWidth, imgHeight) > w) {
          if (imgWidth > imgHeight) {
            canvas.width = w;
            canvas.height = (w * imgHeight) / imgWidth;
          } else {
            canvas.height = w;
            canvas.width = (w * imgWidth) / imgHeight;
          }
        } else {
          canvas.width = imgWidth;
          canvas.height = imgHeight;
        }
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.drawImage(newImage, 0, 0, canvas.width, canvas.height);
        // // 文件下载  二进制文件保存为图片
        // canvas.toBlob((blob) => {
        //     // console.log(blob, file)
        //     // return blob

        //     // // 创建隐藏的可下载链接
        //     let eleLink = document.createElement('a')
        //     eleLink.download = '1'
        //     eleLink.style.display = 'none'
        //     eleLink.href = URL.createObjectURL(blob)
        //     // 触发点击
        //     document.body.appendChild(eleLink)
        //     eleLink.click()
        //     // 然后移除
        //     document.body.removeChild(eleLink)
        //   }, 'image/jpg')
        var base64 = canvas.toDataURL(getMimeType(base64String), quality);
        // // base64保存为图片文件
        // let eleLink = document.createElement("a");
        // eleLink.download = "1";
        // eleLink.style.display = "none";
        // eleLink.href = base64;
        // // 触发点击
        // document.body.appendChild(eleLink);
        // eleLink.click();
        // // 然后移除
        // document.body.removeChild(eleLink);
        // console.log(base64);
        return base64;
      });
    },

    getimg() {
      var file = this.$refs.img.files[0];
      console.log(file);
      var formdata1 = new FormData(); // 创建form对象
      formdata1.append("img", file, file.name); // 通过append向form对象添加数据,可以通过append继续添加数据
      //或formdata1.append('img',file);
      let config = {
        headers: { "Content-Type": "multipart/form-data" },
      }; //添加请求头
      console.log(formdata1);
      axios
        .post(
          "http://house.ksljz.cn:8081/house/platform/system/sysFile/fileUpload.do",
          formdata1,
          config
        )
        .then((response) => {
          //这里的/xapi/upimage为接口
          console.log(response.data);
        });
    },
  },
  created() {
    this.getMore();

    // 控制背景色
    var bg = document.querySelector("body");
    bg.style.backgroundColor = "#f2f2f2";

    this.optionHeight = (document.documentElement.clientHeight * 60) / 1334;
  },
};
</script>

<style lang='scss' scoped>
#house {
  width: 100%;
  position: relative;
  background-color: #f2f2f2;
  font-size: 12px;
  .bottom-page {
    .head-line {
      display: flex;
      justify-content: space-between;
      align-items: center;
      height: 44px;
      padding: 0 10px;
      color: white;
      font-size: 12px;
      font-family: PingFangSC-Regular, sans-serif;
      background-color: #109beb;
      box-sizing: border-box;
      h2 {
        padding: 0;
      }
      img {
        width: 20px;
        height: 20px;
      }
      span {
        display: inline-block;
        height: 30px;
        width: 40px;
        line-height: 30px;
      }
    }
    .houseInfor {
      padding: 0 10px;
      width: 100%;
      box-sizing: border-box;
      text-align: left;
      h1 {
        margin: 10px 0;
      }
      p {
        display: inline-table;
        width: 50%;
        line-height: 25px;
        &:last-child {
          width: 100%;
        }
      }
    }
    .inspect-list {
      padding: 0 10px;
      width: 100%;
      box-sizing: border-box;
      .inspect-head {
        position: relative;
        text-align: left;
        h1 {
          display: inline-block;
          margin: 10px 0;
        }
        .add {
          position: absolute;
          right: 0;
          bottom: 13px;
          padding: 3px;
          border: 1px solid #ccc;
          border-radius: 3px;
          background-color: #fff;
        }
      }
      .table {
        border: 1px dashed #ccc;
        margin-bottom: 10px;
        .inspect-title {
          width: 100%;
          span {
            display: inline-block;
            width: 20%;
            height: 30px;
            line-height: 30px;
          }
        }
        .house-item {
          background-color: #fff;
          span {
            display: inline-block;
            vertical-align: middle;
            width: 20%;
            line-height: 30px;
            &:last-child {
              color: rgb(84, 159, 230);
            }
          }
        }
        .inspect-item {
          background-color: #fff;
          span {
            display: inline-block;
            vertical-align: middle;
            width: 20%;
            line-height: 30px;
            &:last-child {
              color: rgb(84, 159, 230);
            }
          }
        }
      }
    }
  }
  .demo-out {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100vh;
    z-index: 10;
    background-color: rgba(0, 0, 0, 0.5);
    // > img {
    //   position: absolute;
    //   right: 5%;
    //   top: 5%;
    //   border: 1px solid #fff;
    // }
    .demo-in {
      position: absolute;
      width: 90%;
      // height: 80%;
      margin: 0 auto;
      top: 50%;
      left: 50%;
      padding: 10px;
      border-radius: 5px;
      box-sizing: border-box;
      background-color: #fff;
      transform: translate(-50%, -50%);
      // overflow: hidden;
      .demo-inner {
        width: calc(100%);
        height: calc(100% - 40px);
        overflow-y: auto;
        > div {
          width: 100%;
          text-align: left;
          span {
            display: inline-block;
            line-height: 25px;
            width: 100px;
          }
          input {
            border: 1px solid rgb(170, 170, 170);
          }
          &.textarea {
            margin-top: 10px;
            span {
              vertical-align: top;
            }
            textarea {
              border: 1px solid rgb(170, 170, 170);
            }
          }
        }
        .rectifyDemo {
          .textarea {
            margin-top: 10px;
            span {
              vertical-align: top;
            }
            textarea {
              border: 1px solid rgb(170, 170, 170);
            }
          }
        }
      }
      .btns {
        // position: absolute;
        // bottom: 0px;
        // left: 10px;
        width: 100%;
        // height: 50px;
        // margin-top: 10px;
        text-align: center;
        button {
          padding: 5px 10px;
          margin: 0 10px;
        }
      }
    }
  }
}
</style>
